import vue from '@vitejs/plugin-vue';
import { defineConfig, externalizeDepsPlugin } from 'electron-vite';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import viteCompression from 'vite-plugin-compression';
import VueDevTools from 'vite-plugin-vue-devtools';

// Helper function to safely get environment variables with defaults
const getEnv = (key: string, defaultValue: string = ''): string => process.env[key] ?? defaultValue;

const VITE_API_LOCAL = getEnv('VITE_API_LOCAL', '/api-local');
const VITE_API = getEnv('VITE_API', 'http://localhost:3000'); // Example default target
const VITE_API_MUSIC_PROXY = getEnv('VITE_API_MUSIC_PROXY', '/api-music');
const VITE_API_MUSIC = getEnv('VITE_API_MUSIC', 'http://localhost:4000'); // Example default target
const VITE_API_PROXY_MUSIC = getEnv('VITE_API_PROXY_MUSIC', '/api-proxy');
const VITE_API_PROXY = getEnv('VITE_API_PROXY', 'http://localhost:5000'); // Example default target

export default defineConfig(({ command }) => ({
  main: {
    plugins: [externalizeDepsPlugin()]
  },
  preload: {
    plugins: [externalizeDepsPlugin()]
  },
  renderer: {
    resolve: {
      alias: {
        '@': resolve('src/renderer'),
        '@renderer': resolve('src/renderer')
      }
    },
    plugins: [
      vue(),
      viteCompression(),
      // Only enable VueDevTools during development (serve command)
      command === 'serve' ? VueDevTools() : undefined,
      AutoImport({
        imports: [
          'vue',
          {
            'naive-ui': ['useDialog', 'useMessage', 'useNotification', 'useLoadingBar']
          }
        ]
      }),
      Components({
        resolvers: [NaiveUiResolver()]
      })
    ].filter(Boolean), // Filter out undefined plugins
    server: {
      proxy: {
        // Use the variables with defaults
        [VITE_API_LOCAL]: {
          target: VITE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_API_LOCAL}`), '')
        },
        [VITE_API_MUSIC_PROXY]: {
          target: VITE_API_MUSIC,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_API_MUSIC_PROXY}`), '')
        },
        [VITE_API_PROXY_MUSIC]: {
          target: VITE_API_PROXY,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_API_PROXY_MUSIC}`), '')
        }
      }
    }
  }
}));
